<?php
/**
 * ERROR CODE 0400-0499
 *
 * */
define("MONTH_1", 2592000);
class User {
	private $error;
	public function __construct(){
		if( empty($this->error) ) {
			if( !empty($GLOBALS['error']) ) {
				$this->error = $GLOBALS['error'];
			} else {
				$this->error = new Error();
				$GLOBALS['error'] = &$this->error;
			}
		}
		session_set_cookie_params(MONTH_1);
		session_name("s_user");
		session_start();
	}
	public function userID() {
		return $this->userInfo("user_id");
	}
	public function userGroup() {
		$ret = "user";
		$id = $this->userInfo("user_id");
		if(  $id != -1 ) {
			$ret = "admin";
		}
		return $ret;
	}
	public function login( $login, $password ) {
		$ret = array();
		$ret['status'] = false;
		$db = new DB();
		$sql = "SELECT `id` AS `user_id`, `object_id`, `session_id` FROM `user_admin` WHERE `login` = '{$login}' AND `password` = '{$password}'";
		$res = $db->query($sql);
		if( $res === false ){
			return false;
		}
		if( empty($res) ) {
			return $ret;
		}
		$ret['status'] = true;
		$ret = @array_merge($ret, $res);
		if( !empty($res['session_id']) ) {
			$path = session_save_path();
			$delFile = $path."/sess_".$res['session_id'];
			if( file_exists($delFile) )
				unlink($path."/sess_".$res['session_id']);
		}
		$this->writeSession($res);
		$sql = "UPDATE `user_admin` SET `session_id` = '{$_SESSION['s_user']}' WHERE `id` = {$res['user_id']}";
		$res = $db->query($sql);
		if( $res === false ){
			return false;
		}
		return $ret;
	}
	private function writeSession( array $array ) {
		if( empty($array) ) {
			return true;
		}
		$_SESSION = array_merge( $_SESSION,$array );
		$this->setUnicCookie();
		return true;
	}
	private function setUnicCookie() {
		$_SESSION['s_user'] = session_id();
		$uniqId = md5(uniqid());
		@setcookie ("c_user", $uniqId,time()+MONTH_1,"/");
		$_SESSION['c_user'] = $uniqId;
	}
	private function userInfo( $key ) {
		if( $_SESSION['s_user'] == session_id() && isset($_COOKIE['c_user']) && $_COOKIE['c_user'] == $_SESSION['c_user'] ) {
			if( isset($key) ) {
				$this->setUnicCookie();
				$ret = -1;
				if( array_key_exists($key, $_SESSION) ) {
					$ret = $_SESSION[$key];
				}
				return $ret;;
			}
		} else {
			return -1;
		}
	}
}
?>